// TCP Select Server
// 
// A TCP Select Server which returns everything the client sends to it. Based on example code written by Richard Blum in the book C# Network Programming.
// 
// Author: F.M.A. Erich
// HAN University of Applied Science
// Arnhem, The Netherlands

using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SelectServer
{
	public class SelectTcpSrvr
	{
		public static void Main()
		{
			ArrayList sockList = new ArrayList();
			ArrayList copyList = new ArrayList();
			Socket main = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
	      
			main.Bind(iep);
			main.Listen(2);
	
		    while(true)
			{
				if (main.Poll(10, SelectMode.SelectRead))
				{
					Socket client = main.Accept();
					IPEndPoint ciep = (IPEndPoint)client.RemoteEndPoint;
					Console.WriteLine("Connected to {0}", ciep.ToString());
					sockList.Add(client);
				}
				else if (sockList.Count > 0) {
					Boolean lastClient = false;
					foreach(Socket client in copyList) {
						byte[] data = new byte[1024];
		      			string stringData;
		      			int recv;
							
			            data = new byte[1024];
			            recv = client.Receive(data);
						
			            stringData = Encoding.ASCII.GetString(data, 0, recv);
			            Console.WriteLine("Received: {0}", stringData);
			            if (recv == 0)
			            {
							iep = (IPEndPoint)client.RemoteEndPoint;
							Console.WriteLine("Client {0} disconnected.", iep.ToString());
							client.Close();
							sockList.Remove(client);
							if (sockList.Count == 0) lastClient = true;
						}
						else
							client.Send(data, recv, SocketFlags.None);
						continue;
					}
					if (lastClient) continue;
				} else continue;
				copyList = new ArrayList(sockList);
				Socket.Select(copyList, null, null, 10);
			}
		}
	}
}